package com.fjh.security.easy.starter.authentication.handler;

import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fjh.security.easy.starter.authentication.service.EasyAuthLogoutSuccessService;
import com.fjh.security.easy.starter.util.HttpSessionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * 登录退出
 *
 * @author fanjh37
 * @since 2023/2/12 18:13
 */
@Slf4j
public class JsonLogoutSuccessHandler implements LogoutSuccessHandler {

    @Autowired(required = false)
    private EasyAuthLogoutSuccessService easyAuthLoginSuccessService;

    @Override
    public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        if (Objects.nonNull(authentication)) {
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            log.info("-----用户：{} 退出登录", userDetails.getUsername());
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 0);
        jsonObject.put("msg", "退出登录成功");
        httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
        httpServletResponse.setCharacterEncoding(StandardCharsets.UTF_8.name());
        httpServletResponse.getWriter().write(new ObjectMapper().writeValueAsString(jsonObject));
        if (Objects.nonNull(easyAuthLoginSuccessService)) {
            easyAuthLoginSuccessService.onLogoutSuccess(httpServletRequest, httpServletResponse, authentication);
        }
    }
}
